{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This notebook is used to initialize the directory structure for the materials directory using an example YAML (or json) file of a Materials Project document."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "import os\n",
    "import re\n",
    "import shutil\n",
    "\n",
    "import yaml"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "CONFIG = {\n",
    "    \"materials\": {\n",
    "        \"rootdir\": \"../materials\",\n",
    "        \"fname_pattern\": r\"^material_.+\\.yaml$\"\n",
    "    },\n",
    "    \"tasks\": {\n",
    "        \"rootdir\": \"../tasks\",\n",
    "        \"fname_pattern\": r\"^task_.+\\.yaml$\"\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "desired = set()\n",
    "\n",
    "example = \"\"\"## Example response in JSON\n",
    "\n",
    "```json\n",
    "%s\n",
    "```\n",
    "\n",
    "\"\"\"\n",
    "\n",
    "def make_dir(d, rootdir):\n",
    "    for k, v in d.items():\n",
    "        if k == \"_id\":\n",
    "            # Ignore object id key, which is useless.\n",
    "            continue\n",
    "        subpath = os.path.join(rootdir, k)\n",
    "        try:\n",
    "            os.makedirs(subpath)\n",
    "        except:\n",
    "            pass\n",
    "        fname = os.path.join(subpath, \"README.md\")\n",
    "        desired.add(subpath)\n",
    "        desired.add(fname)\n",
    "        if not os.path.exists(fname):\n",
    "            with open(fname, \"w\") as f:\n",
    "                if v is not None:\n",
    "                    data = example % json.dumps(v, indent=4)\n",
    "                else:\n",
    "                    data = \"\"\n",
    "                f.write(data)\n",
    "        else:\n",
    "            with open(fname) as f:\n",
    "                data = f.read().strip()\n",
    "            data = data.split(\"## Example response in JSON\")[0]\n",
    "            if \"## Example response in JSON\" not in data:\n",
    "                if v is not None:\n",
    "                    data += \"\\n\\n\"\n",
    "                    data += example % json.dumps(v, indent=4)\n",
    "                    with open(fname, \"w\") as f:\n",
    "                        print(f\"Adding example to {k}\")\n",
    "                        f.write(data)\n",
    "\n",
    "        if isinstance(v, dict) and \"formula\" not in k:\n",
    "            # Ignore formulas which has material specific keys.\n",
    "            make_dir(v, rootdir=subpath)\n",
    "        elif isinstance(v, list) and len(v) and isinstance(v[0], dict):\n",
    "            # Recurse into lists of dicts\n",
    "            make_dir(v[0], rootdir=subpath)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for k, v in CONFIG.items():\n",
    "    print(f\"Generating for {k}...\")\n",
    "    for fname in [fname for fname in os.listdir('.') if re.match(v[\"fname_pattern\"], fname)]:\n",
    "        with open(fname) as f:\n",
    "            doc = yaml.load(f)\n",
    "        make_dir(doc, rootdir=v[\"rootdir\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import glob\n",
    "from tqdm import tqdm_notebook as tqdm\n",
    "\n",
    "for k, v in CONFIG.items():\n",
    "    print(f\"Cleanup for {k}...\")\n",
    "    rootdir = v[\"rootdir\"]\n",
    "\n",
    "    desired = {d for d in desired if f\"{rootdir}/sbxn\" not in d or f\"{rootdir}/sbxd\" not in d}\n",
    "    paths_to_kill = set(glob.glob(f\"{rootdir}/**\", recursive=True))\n",
    "    paths_to_kill -= desired\n",
    "    paths_to_kill -= {f\"{rootdir}/\"}\n",
    "    paths_to_kill =  {d for d in desired if f\"{rootdir}/sbxn\" in d or f\"{rootdir}/sbxd\" in d}\n",
    "\n",
    "    for path in tqdm(paths_to_kill):\n",
    "        try:\n",
    "            os.remove(path)\n",
    "        except OSError:\n",
    "            try:\n",
    "                os.removedirs(path)\n",
    "            except OSError:\n",
    "                pass"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
